package tk.mybatis.springboot.common.util;

import java.io.*;

/**
 * Created by jie_r on 2017/2/16.
 */
public class FileUtil {

    /**
     * 获得文件的byte数组
     *
     * @param filePath 文件地址
     * @return
     */
    public static byte[] getBytes(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 保存文件
     *
     * @param inputStream
     * @param out         文件保存地址
     * @return
     */
    public static boolean saveFile(InputStream inputStream, String out) {
        String path = out.substring(0, out.lastIndexOf("/"));
        File parent = new File(path);
        if (!parent.exists()) {
            parent.mkdirs();
        }
        try {
            //获取输出流
            OutputStream outputStream = new FileOutputStream(out);
            int temp;
            byte[] buf = new byte[1024];
            while ((temp = inputStream.read(buf)) != (-1)) {
                outputStream.write(buf, 0, temp);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除文件
     *
     * @param filePath
     */
    public static boolean delFile(String filePath) {
        if (StringUtil.isEmpty(filePath)) {
            return false;
        }
        File file = new File(filePath);
        if (file.exists()) {
            return file.delete();
        } else {
            return false;
        }
    }

    /**
     * 文件是否存在
     *
     * @param filePath
     */
    public static boolean isExistsFile(String filePath) {
        if (StringUtil.isEmpty(filePath)) {
            return false;
        }
        File file = new File(filePath);
        return file.exists();
    }
}
